<?php

namespace App\Console\Commands;

use App\Exceptions\Admin\V1\GeneralException;
use App\Extensions\Log\V1\InstanceLog;
use App\Models\V1\UserOauth;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;

class AppendUnionIdToUserOauth extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'useroauth:append-unionid';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'append unionid to user oauth table';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GeneralException
     */
    public function handle()
    {
        /*
         * 目标：将user_oauth表中的wechat_union_id字段数据迁移至对应的old_wechat_union_id字段中区
         * 1. 获取user_oauth表中wechat_union_id的数据
         * 2. 将数据写入user_oauth表中old_wechat_union_id字段中
         **/
        // 方式1：
        /*$this->info("\n本次任务开始执行，目标是：将user_oauth数据表中的wechat_union_id字段值迁移至old_wechat_union_id字段!");
        $tableHeaders = [
            'name', 'success', 'fault'
        ];
        $usersCount = UserOauth::all()->count();
        $bar = $this->output->createProgressBar($usersCount);
        $bar->start();
        UserOauth::select(['id', 'wechat_union_id'])->chunk(100, function ($users) use ($bar) {
            foreach ($users as $user) {
                $user->old_wechat_union_id = $user->wechat_union_id;
                $user->save();
            }
            $bar->advance(100);
        });
        $bar->finish();
        $this->info("\n本次任务执行成功，具体情况如下：");
        $result = [['迁移wechat_union_id', $usersCount, 0]];
        $this->table($tableHeaders, $result);*/

        // 方式2：
        try {
            DB::update('UPDATE user_oauth a,(SELECT id,wechat_union_id as wuid from user_oauth) b set a.old_wechat_union_id=b.wuid where a.id = b.id');
        } catch (ModelNotFoundException $exception) {
            InstanceLog::instance('admin')->error('迁移数据失败：' . $exception->getMessage());

            throw new GeneralException(GeneralException::GENERAL_DATA_FIND__WITHOUT);
        }
    }
}
